package com.hyjx.framework.common.util;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import com.hyjx.framework.common.CommonUtil;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;
import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.ConnectException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

@SuppressWarnings("restriction")
public class DocToPDFConverter {
    private static Logger logger = LoggerFactory.getLogger(DocToPDFConverter.class);
    private static final int environment = 1;// 环境 1：windows 2:linux

    public static String office2PDF(String sourceFile, String pdfpath, String picPath) {
        try {
            logger.debug("--------开始转化文件：" + sourceFile + "--------------");
            File inputFile = new File(sourceFile);
            if (!inputFile.exists()) {
                return "fail,filenotfind";// 找不到源文件, 则返回-1  
            }
            String pdfName = CommonUtil.getUUID32() + ".pdf";
            String destFile = pdfpath + pdfName;
            // 如果目标路径不存在, 则新建该路径  
            File outputFile = null;
            if (sourceFile.toLowerCase().endsWith("pdf")) {
                copyFile(sourceFile, destFile);
                outputFile = new File(destFile);
            } else {
                outputFile = new File(destFile);
                if (!outputFile.getParentFile().exists()) {
                    outputFile.getParentFile().mkdirs();
                }
                //soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard
                OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
                connection.connect();
                DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
                converter.convert(inputFile, outputFile);
                connection.disconnect();
            }
            String imgName = "";
            if (picPath != null && !"".equals(picPath)) {
                File file1 = new File(picPath);
                if (!file1.exists()) {
                    file1.mkdir();
                }
                imgName = createScreenShoot(outputFile, picPath);//生成图片。
            }
            String temppdfName = "";
            if (pdfpath != null && !"".equals(pdfpath)) {
                File file = new File(pdfpath);
                if (!file.exists()) {
                    file.mkdir();
                }
                temppdfName = getNewPDF(outputFile, "1-2", pdfpath);//截取pdf
            }
            //String tempswf = pdf2swf(outputFile,pdfpath);
            logger.info("转换的pdf名为：" + pdfName);
//            if("fail".equals(tempswf)){
//            	return "fail,fail3";
            if ("fail".equals(temppdfName)) {
                return "fail,fail1";
            } else if ("fail".equals(imgName)) {
                return "fail,fail2";
            }
            return temppdfName + "," + imgName;
        } catch (ConnectException e) {
            e.printStackTrace();
            return "fail,fail";
        }
    }

    /**
     * pdf截取两页的pdf
     *
     * @param file
     * @param num
     * @param path
     * @return
     */
    public static String getNewPDF(File file, String num, String path) {
        try {
            String str = CommonUtil.getUUID32();
            PdfReader pdfReader = new PdfReader(new FileInputStream(file));
            PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream(path + str + ".pdf"));
            pdfReader.selectPages(num);
            pdfStamper.close();
            logger.info("截取的pdf名为：" + str + ".pdf");
//            String tempswfstr = pdf2swf(new File(path+str+".pdf"), path);
//            if("fail".equals(tempswfstr)){
//            	logger.error("转换swf失败");
//    			return "fail";
//            }else{
//            	return tempswfstr;
//            }
            return path + str + ".pdf";
        } catch (FileNotFoundException e) {
            logger.error("截取pdf失败", e);
            return "fail";
        } catch (IOException e) {
            logger.error("截取pdf失败", e);
            return "fail";
        } catch (DocumentException e) {
            logger.error("截取pdf失败", e);
            return "fail";
        }
    }

    /**
     * pdf生成图片
     *
     * @param file
     * @param target
     * @return
     */
    public static String createScreenShoot(File file, String target) {
        if (!file.exists()) {
            logger.info("路径[" + file.getPath() + "]对应的pdf文件不存在!");
            return "";
        }
        try {
            RandomAccessFile raf = new RandomAccessFile(file, "r");
            FileChannel channel = raf.getChannel();
            ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
            PDFFile pdffile = new PDFFile(buf);
            int num = pdffile.getNumPages();
//		        if(num>2){
//		        	num=2;
//		        }
//		        for(int i = 0; i < num; i++){
            String str = CommonUtil.getUUID32();
            PDFPage page = pdffile.getPage(1);

            // get the width and height for the doc at the default zoom
            Rectangle rect = new Rectangle(0, 0, (int) page.getBBox()
                    .getWidth(), (int) page.getBBox().getHeight());

            // generate the image
            Image img = page.getImage(rect.width, rect.height, // width &
                    rect, // clip rect
                    null, // null for the ImageObserver
                    true, // fill background with white
                    true // block until drawing is done
            );

            BufferedImage tag = new BufferedImage(rect.width, rect.height, BufferedImage.TYPE_INT_RGB);
            tag.getGraphics().drawImage(img, 0, 0, rect.width, rect.height, null);
            //JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            //encoder.encode(tag); // JPEG编码
            // out.close();
//		        }
            logger.info("转换的图片名为：" + str + ".jpg");
            return str + ".jpg";
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("转换图片失败", e);
            return "893c482c95424b808871708dac974e90.jpg";
        }
    }

    /**
     * 转换成 swf
     */
    @SuppressWarnings("unused")
    public static String pdf2swf(File pdfFile, String pdfpath) {
        String swfName = CommonUtil.getUUID32() + ".swf";
        File swfFile = new File(pdfpath + swfName);
        Runtime r = Runtime.getRuntime();
        if (pdfFile.exists()) {
            if (environment == 1) {// windows环境处理
                try {


                    String command = "\"C:\\Program Files (x86)\\SWFTools\\pdf2swf.exe\"" + " -o \"" + pdfpath + "\\" + swfName + "\"  -s languagedir=D:\\xpdf\\xpdf-chinese-simplified -s flashversion=9 \"" + pdfFile.getPath() + "\"";
                    Process p = r.exec(command);
//					Process p = r.exec("C:/Program Files (x86)/SWFTools/pdf2swf.exe "+ pdfFile.getPath() + " -o "+ swfFile.getPath() + " -T 9");

                    logger.info(loadStream(p.getInputStream()));
                    logger.info(loadStream(p.getErrorStream()));
                    logger.info("****swf转换成功，文件输出："
                            + swfFile.getPath() + "****");
                    if (pdfFile.exists()) {
                        pdfFile.delete();
                    }
                    return swfFile.getName();
                } catch (IOException e) {
                    logger.error("转换swf失败", e);
                    return "fail";
                }
            } else if (environment == 2) {// linux环境处理
                try {
                    Process p = r.exec("pdf2swf " + pdfFile.getPath()
                            + " -o " + swfFile.getPath() + " -T 9");
                    logger.info(loadStream(p.getErrorStream()));
                    logger.info(loadStream(p.getInputStream()));
                    logger.info("****swf转换成功，文件输出："
                            + swfFile.getPath() + "****");
                    if (pdfFile.exists()) {
                        pdfFile.delete();
                    }
                    return swfFile.getName();
                } catch (Exception e) {
                    logger.error("转换swf失败", e);
                    return "fail";
                }
            }
        } else {
            logger.error("****pdf不存在,无法转换****");
            return "fail";
        }
        return swfName;
    }

    static String loadStream(InputStream in) throws IOException {

        int ptr = 0;
        in = new BufferedInputStream(in);
        StringBuffer buffer = new StringBuffer();

        while ((ptr = in.read()) != -1) {
            buffer.append((char) ptr);
        }

        return buffer.toString();
    }

    public static void copyFile(String oldPath, String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { //文件存在时
                File outputFile = new File(newPath);
                if (!outputFile.getParentFile().exists()) {
                    outputFile.getParentFile().mkdirs();
                }
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                int length;
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        } catch (Exception e) {
            logger.error("复制单个文件操作出错");
            e.printStackTrace();

        }

    }

    public static void main(String[] args) {

        String str = DocToPDFConverter.office2PDF("d:/123.doc", "d:/", "d:/");
        //String str = pdf2swf(new File("d:/test-new.pdf"),"d:/");
        System.out.println(str);
    }
}
